#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
import django
import djangoproject
import COOPIP_Authentication, COOPIP_Form, COOPIP_FormCOOPTalk

import httplib


def COOPTalkTestHarness(request):
    """View that allows COOPTalk Commands to be sent and received to test response times, responses, and functionality."""

    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Engineering'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/cooptalktestharness.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))


    import datetime
 
    SpecialBuildFormDataDict={'request': request}
    form=COOPIP_Form.BuildDynamicForm(request, 'COOPTalkTestHarness', SpecialBuildFormDataDict)
    TimeLogs, DataSent, ResponseReceived = COOPIP_FormCOOPTalk.ProcessTestHarnessForm(form, Username)
    form=COOPIP_FormCOOPTalk.PopulateTestHarnessForm(form)

    t = loader.get_template('/opt/coopip/djangoproject/templates/cooptalktestharness.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission, 'TimeLogs': TimeLogs, 'DataSent': DataSent, 'ResponseReceived': ResponseReceived})
    return HttpResponse(t.render(c))




def COOPTalkViewLog(request):
    """View that gives listing of recent COOPTalk Events for troubleshooting/diagnostic purposes"""

    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_Engineering'])
    if(not Permission):
        t = loader.get_template('/opt/coopip/djangoproject/templates/cooptalkviewlog.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))


    import datetime
    StartDateTime=datetime.datetime.now() - datetime.timedelta(hours=4)
    Rows=COOPTalk.objects.filter(CreateDateTime__gte=StartDateTime).order_by('-CreateDateTime')
    

    t = loader.get_template('/opt/coopip/djangoproject/templates/cooptalkviewlog.html')
    c = Context({'LoginStatus': LoginStatus, 'Permission': Permission, 'Rows':Rows })
    return HttpResponse(t.render(c))





def COOPTalkView(request):
    """COOPTalk View handles incoming COOPTalk requests"""
    Input=str(request.POST)
    ActualResponse=''
    cOOPTalk = COOPTalk()
    if('<PingURL xmlns="http://www.multispeak.org/Version_3.0" />' in Input):
        Response=cOOPTalk.InResponsePingURL(Input)
    elif('<GetMethods xmlns="http://www.multispeak.org/Version_3.0" />' in Input):
        Response=cOOPTalk.InResponseGetMethods(Input)
    elif('<ReadingChangedNotification xmlns="http://www.multispeak.org/Version_3.0">' in Input):
        try:
            Response=cOOPTalk.InResponseReadingChangedNotification(Input)
        except:
            Response=('An Exception Occurred.' + str(sys.exc_info()[0]))
            ActualResponse='An Exception Occurred.'
    else:
        Response=cOOPTalk.InResponsePingURL(Input)



    if(ActualResponse):
        Response=ActualResponse
    return HttpResponse(Response, mimetype='text/xml')










